import { ref, customRef, createApp, h } from 'vue'

let loadingWrapper = null
let appInstance = null

const LoadingComponent = {
  name: 'GlobalLoading',
  render() {
    return h(
      'div',
      {
        style: {
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100vw',
          height: '100vh',
          background: 'rgba(0,0,0,0.35)',
          zIndex: 99999,
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }
      },
      [
        h(
          'div',
          {
            style: {
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '18px'
            }
          },
          [
            h(
              'svg',
              {
                width: '70',
                height: '70',
                viewBox: '0 0 50 50',
                style: {
                  display: 'block',
                  // Animate via CSS
                  animation: 'global-spin 1s linear infinite'
                }
              },
              [
                h('circle', {
                  cx: '25',
                  cy: '25',
                  r: '20',
                  fill: 'none',
                  stroke: '#fff',
                  'stroke-width': '6',
                  'stroke-linecap': 'round',
                  'stroke-dasharray': '90 70', // creates a beautiful arc
                  'stroke-dashoffset': '-35',
                  opacity: '0.85'
                })
              ]
            ),
            h(
              'span',
              {
                style: {
                  color: '#fff',
                  fontWeight: 500,
                  fontSize: '18px',
                  letterSpacing: '1.5px',
                  textShadow: '0 2px 12px rgba(0,0,0,0.25)'
                }
              },
              '加载中...'
            ),
            // inline style element for keyframes
            h('style', {}, `
              @keyframes global-spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg);}
              }
            `)
          ]
        )
      ]
    )
  }
}

export const useGlobalLoading = () => {
  const loadingCount = ref(0)
  
  const loading = customRef((track, trigger) => ({
    get() {
      // 收集依赖
      track()
      return loadingCount.value > 0
    },
    set(value) {
      if (value) {
        loadingCount.value++
      } else if (loadingCount.value > 0) {
        loadingCount.value--
      }
      // 触发依赖
      trigger()
    }
  }))

  const mountLoading = () => {
    if (loadingWrapper) return
    loadingWrapper = document.createElement('div')
    loadingWrapper.setAttribute('id', 'global-loading-app')
    document.body.appendChild(loadingWrapper)
    appInstance = createApp(LoadingComponent)
    appInstance.mount(loadingWrapper)
  }

  const unmountLoading = () => {
    if (loadingWrapper && appInstance && loadingCount.value === 0) {
      appInstance.unmount()
      if (loadingWrapper.parentNode) {
        loadingWrapper.parentNode.removeChild(loadingWrapper)
      }
      loadingWrapper = null
      appInstance = null
    }
  }

  const startLoading = () => {
    loading.value = true
    mountLoading()
  }

  const stopLoading = () => {
    loading.value = false
    if (loadingCount.value === 0) {
      unmountLoading()
    }
  }

  return {
    loading,
    startLoading,
    stopLoading,
  }
}

/**
 * 使用方法
 * const { loading, startLoading, stopLoading } = useGlobalLoading()
 * 
 * 在需要加载的地方调用 startLoading()
 * 在加载完成后调用 stopLoading()
 * 
 * 在组件中使用
 * 
 * 例如在axios 拦截器中startLoading，在请求完成后stopLoading
 * 
 * */ 